<template>
  <div>
    <el-tree-v2
      ref="tree"
      accordion
      :data="tree"
      :default-expanded-keys="['0-0']"
      :height="730"
      highlight-current
      node-key="id"
      :props="treeProps"
      :show-checkbox="showCheckbox"
      style="max-width: 600px"
      @check-change="onCheckChange"
      @node-click="onNodeClick"
    />
  </div>
</template>

<script>
  import { arrToTree, findPathToRoot } from '@/utils/tool.js'
  import { $buildingTree } from '@/api/dic.js'
  export default {
    props: {
      type: {
        type: String,
        default: '4',
      },

      showCheckbox: {
        type: Boolean,
        default: false,
      },
    },

    emits: ['change', 'check-change'],
    data() {
      return {
        treeList: [],
        tree: [],
        treeProps: {
          children: 'children',
          label: 'name',
        },
      }
    },

    mounted() {
      this.load()
    },

    methods: {
      load() {
        this.request()
      },

      request() {
        const sendData = {
          type: this.type,
        }
        $buildingTree(sendData).then((res) => {
          // res.data 中id重复, type + id 为唯一值
          res.data.forEach((item) => {
            item._id = item.id
            item.id = `${item.type}-${item.id}`
            item._pid = item.pid
            item.pid = `${item.type - 1}-${item.pid}`
          })
          this.treeList = res.data
          this.tree = arrToTree(res.data)
        })
      },

      onNodeClick(d, node) {
        if (d.type === '0') {
          node.expanded = true
        }

        const data = {
          nodeType: d.type,
          nodeId: d._id,
        }

        const path = findPathToRoot(d.id, this.treeList)
        this.$emit('change', data, path)
      },

      onCheckChange(data, checked, indeterminate) {
        const nodes = this.$refs.tree.getCheckedNodes()
        const keys = this.$refs.tree.getCheckedKeys()

        this.$emit('check-change', { nodes, keys })
      },

      setKeys(keys) {
        this.$refs.tree.setCheckedKeys(keys)
        this.onCheckChange()
      },

      arrToTree(data) {
        return arrToTree(data)
      },
    },
  }
</script>

<style lang="scss" scoped>
  ::v-deep .el-tree-node .is-current {
    background-color: var(--el-tree-node-hover-bg-color);
  }
</style>
